//
// Created by hsj on 2024-1-4.
// 编译：gcc udp_hello_client_win.c -LH:\mingw\mingw64\x86_64-w64-mingw32\lib -lws2_32 -o udp_hello_client_win
//

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include <fcntl.h>

#ifdef WIN32
//windows minGW64
//inet_ntop函数：_WIN32_WINNT
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0600
#include <winsock2.h>
#include <ws2tcpip.h>
//#pragma comment(lib,"ws2_32.lib")
#else
//linux  gcc
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#endif

#define BUF_SIZE 30
void ErrorHandling( char *message);

int main(int argc, char *argv[] ) {
    char ip[]="127.0.0.1";
    char port[]="8888";

    WSADATA wsaData;
    SOCKET sock;
    char message[BUF_SIZE] ;
    int strLen;
    SOCKADDR_IN servAdr;
//    if(argc!=3) {
//        printf("Usage : %s <IP> <port>\n", argv[0]);
//        exit(1);
//    }
    if(WSAStartup(MAKEWORD(2, 2),&wsaData)!=0)
        ErrorHandling("WSAStartup() error!");

    sock=socket(PF_INET, SOCK_DGRAM, 0);
    if(sock==INVALID_SOCKET)
        ErrorHandling("socket() error");

    memset(&servAdr, 0, sizeof(servAdr));
    servAdr.sin_family=AF_INET;
    servAdr.sin_addr.s_addr=inet_addr(/*argv[1]*/ip);
    servAdr.sin_port=htons(atoi(/*argv[2]*/port));

    connect(sock, (SOCKADDR* )&servAdr, sizeof(servAdr));//改用connect

    while(1) {//死循环
        fputs("Insert message(q to quit): ", stdout);
        fgets(message, sizeof(message), stdin);

        if (!strcmp(message, "q\n") || !strcmp(message, "Q\n"))
            break;

        send(sock, message, strlen(message), 0); //改用connect

        strLen=recv(sock, message, sizeof(message)-1, 0);//改用connect

        message[strLen]=0;
        printf( "Message from server: %s", message);
    }
    closesocket(sock);
    WSACleanup();

    return EXIT_SUCCESS;
}

void ErrorHandling( char *message){
    fputs (message, stderr);
    fputc('\n', stderr);
    exit(1);
}
